﻿namespace EyeOpen.IO
{
	using System;
	using System.IO;
	using System.Linq;

	public class DirectorySearch
	{
		public FileInfo Search(IDirectoryInfo directory, string fileName, ILogger logger)
		{
			try
			{
				var file = directory.GetFiles(fileName).SingleOrDefault();

				if (file != null)
				{
					return file;
				}

				var directories = directory.GetDirectories();

				if (directories.Count() == 0)
				{
					return null;
				}

				foreach (var child in directories)
				{
					logger.Trace(child.FullName);

					var fileFound = Search(child, fileName, logger);

					if (fileFound != null)
					{
						return fileFound;
					}
				}
			}
			catch (Exception ex)
			{
				logger.Exception(ex);
				return null;				
			}

			return null;
		}
	}
}